package com.fhx.core

import android.annotation.SuppressLint
import android.content.Context
import android.content.res.Configuration
import androidx.multidex.MultiDex
import androidx.multidex.MultiDexApplication
import com.fhx.core.utils.AppLanguageUtils
import com.fhx.core.utils.SharePreferencesUtil

open class AppContext : MultiDexApplication() {

    companion object {
        @SuppressLint("StaticFieldLeak")
        lateinit var instance: Context
    }

    override fun onCreate() {
        super.onCreate()
        instance = this

        onLanguageChange()
    }

    override fun attachBaseContext(base: Context?) {
        super.attachBaseContext(AppLanguageUtils.attachBaseContext(base!!, getAppLanguage(base)!!))
        MultiDex.install(this)
    }

    /**
     * Handling Configuration Changes
     * @param newConfig newConfig
     */
    override fun onConfigurationChanged(newConfig: Configuration?) {
        super.onConfigurationChanged(newConfig)
        onLanguageChange()
    }

    private fun onLanguageChange() {
        AppLanguageUtils.changeAppLanguage(this, AppLanguageUtils.getSupportLanguage(getAppLanguage(this)))
    }

    private fun getAppLanguage(context: Context): String? {
        return SharePreferencesUtil.getString(
            context,
            AppLanguageUtils.LANGUAGE,
            AppLanguageUtils.CHINESE
        )
    }
}